#include "Stdafx.h"
#include "Timer.h"

namespace WindGE
{
	Timer::Timer()
		: second_per_count_(0)
		, delta_time_(0)
		, base_time_(0)
		, pause_time_(0)
		, stop_time_(0)
		, prev_time_(0)
		, cur_time_(0)
		, is_stopped_(false)
	{
		__int64 countsPerSec = 0;
		QueryPerformanceFrequency((LARGE_INTEGER*)&countsPerSec);
		second_per_count_ = 1.0 / (double)countsPerSec;
	}

	void Timer::reset()
	{
		__int64 curTime = 0;
		QueryPerformanceCounter((LARGE_INTEGER*)&curTime);
		
		base_time_ = curTime;
		prev_time_ = curTime;
		stop_time_ = 0;
		is_stopped_ = false;
	}

	void Timer::start()
	{
		__int64 startTime = 0;
		QueryPerformanceCounter((LARGE_INTEGER*)&startTime);

		if (is_stopped_)
		{
			pause_time_ += (startTime - stop_time_);
			prev_time_ = startTime;
			stop_time_ = 0;
			is_stopped_ = false;
		}
	}

	void Timer::stop()
	{
		if (!is_stopped_)
		{
			__int64 curTime = 0;
			QueryPerformanceCounter((LARGE_INTEGER*)&curTime);

			stop_time_ = curTime;
			is_stopped_ = true;
		}
	}

	void Timer::tick()
	{
		if (is_stopped_)
		{
			delta_time_ = 0;
			return;
		}

		__int64 curTime = 0;
		QueryPerformanceCounter((LARGE_INTEGER*)&curTime);
		cur_time_ = curTime;

		delta_time_ = (cur_time_ - prev_time_) * second_per_count_;
		
		prev_time_ = cur_time_;

		if (delta_time_ < 0.0)
		{
			delta_time_ = 0.0;
		}
	}

}//end namespace WindGE


